//
//  Status.swift
//  SwiftWeiBo
//
//  Created by wyw on 16/10/17.
//  Copyright © 2016年 Style_Y. All rights reserved.
//

import UIKit

class Status: NSObject {
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String?
    /// 配图数组
    var pic_urls: [[String: AnyObject]]?
    
    // 字典转模型
    init(dict : [String : AnyObject]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    // 空的key直接调用这个方法略过
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    // 打印
    let properties = ["created_at","id","text","source","pic_urls"]
    
    override var description: String {
        let dict = dictionaryWithValues(forKeys: properties)
        
      return "\(dict)"
    }
    
    /// 加载微博数据
    class func loadStatuses(_ finished: @escaping (_ models:[Status]?, _ error:NSError?)->()){
        let path = "2/statuses/home_timeline.json"
        let params = ["access_token": UserAccount.loadAccount()!.access_token!]
        
        NetWorkTools.shareNetWorkTools().get(path, parameters: params, progress: nil, success: { (_, JSON) in
            // 1.取出statuses key对应的数组 (存储的都是字典)
            // 2.遍历数组, 将字典转换为模型
            let dict = JSON as! [String : AnyObject]
            let models = dict2Model(dict["statuses"] as! [[String : AnyObject]])
            
            // 2.通过闭包将数据传递给调用者
            finished(models, nil)
            
            }) { (_, error) in
                
                print(error)
                finished(nil, error as NSError?)
        }
    }
    
    /// 将字典数组转换为模型数组
    class func dict2Model(_ list: [[String: AnyObject]]) -> [Status] {
        var models = [Status]()
        for dict in list
        {
            models.append(Status(dict: dict))
        }
        return models
    }
}



















